package com.it.jnxy.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.it.jnxy.Pojo.Result;
import com.it.jnxy.utils.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Component

public class LoginChekInterceptor implements HandlerInterceptor {
    //Controller执行前执行，需要进行拦截 返回true放行，返回flase不放行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求的url
        String url = request.getRequestURL().toString();
        System.out.println("获取的url");
        System.out.println(url);;
        //判断是否为登录请求
        if(url.contains("login")){
            System.out.println("登录操作放行");;
            return true;
        }
        //判断是否为注册请求
        if(url.contains("/register")){
            System.out.println("注册操作放行");;
            return true;
        }
        //获取请求头中的Token
        String jwt = request.getHeader("token");
        //判断令牌是否存在如果不存在返回未登录
        if(!StringUtils.hasLength(jwt)){
            System.out.println("请求头为空，反回未登录信息");;
            Result error = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }
        //令牌存在解析令牌
        try {
            JWTUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("解析令牌失败返回错误信息");;
            Result error = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }
        //放行
        System.out.println("用户合法放行");;
        return true;
    }

    @Override  //目标方法执行后执行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override   //视图渲染完毕后执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
